package com.cskaoyan.gateway.controller.pay;

import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.commons.tool.utils.GetUserInfoUtil;
import com.mall.pay.PayCoreService;
import com.mall.pay.dto.PayRequest;
import com.mall.pay.dto.PaymentRequest;
import com.mall.pay.dto.alipay.AlipayQueryRetResponse;
import com.mall.pay.dto.alipay.AlipaymentResponse;
import com.mall.user.constants.SysRetCodeConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * Author  kkw
 * Date  2021/6/23 19:39
 * Version 1.0
 * Description :
 */
@Slf4j
@RestController
@RequestMapping("cashier")
public class PayController {

    @Reference(timeout = 3000,check = false)
    PayCoreService payCoreService;

    @PostMapping("pay")
    public ResponseData pay(@RequestBody PayRequest payRequest, HttpServletRequest request) {
        PaymentRequest paymentRequest = new PaymentRequest();
        Long uid = GetUserInfoUtil.getUid(request);
        String userName = GetUserInfoUtil.getUserName(request);
        String tradeNo = payRequest.getOrderId();
        paymentRequest.setUserId(uid);
        paymentRequest.setPayerName(userName);
        paymentRequest.setTradeNo(tradeNo);
        paymentRequest.setTotalFee(payRequest.getMoney());
        paymentRequest.setOrderFee(payRequest.getMoney());
        paymentRequest.setSubject(payRequest.getInfo());
        paymentRequest.setPayChannel(payRequest.getPayType());

        AlipaymentResponse response = payCoreService.aliPay(paymentRequest);
        if (!SysRetCodeConstants.SUCCESS.getCode().equals(response.getCode())) {
            log.info("获取支付二维码失败");
            return new ResponseUtil<>().setErrorMsg(response.getMsg());
        }
        String qrCode="http://localhost:8080/image/"+response.getQrCode();
        return new ResponseUtil<>().setData(qrCode);
    }

    @GetMapping("queryStatus")
    public ResponseData queryStatus(String orderId) {
        PaymentRequest paymentRequest = new PaymentRequest();
        paymentRequest.setTradeNo(orderId);
        AlipayQueryRetResponse response = payCoreService.queryAlipayRet(paymentRequest);
        if (!SysRetCodeConstants.SUCCESS.getCode().equals(response.getCode())) {
            log.info("订单未支付");
            return new ResponseUtil<>().setErrorMsg(response.getMsg());
        }
        return new ResponseUtil<>().setData(null);
    }
}
